# -*- coding: utf-8 -*-
import xbmc, xbmcgui, xbmcplugin, xbmcaddon, urllib2, urllib, re, string, sys, os, gzip, StringIO


# Plugin constants
__addonname__ = "美空网"
__addonid__ = "plugin.image.meikong"
__addon__ = xbmcaddon.Addon(id=__addonid__)
__addonicon__ = os.path.join( __addon__.getAddonInfo('path'), 'logo.jpg' )

UserAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'


def GetHttpData(url):
    print "getHttpData: " + url
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)')
    try:
        response = urllib2.urlopen(req)
        httpdata = response.read()
        if response.headers.get('content-encoding', None) == 'gzip':
            httpdata = gzip.GzipFile(fileobj=StringIO.StringIO(httpdata)).read()
        charset = response.headers.getparam('charset')
        response.close()
    except:
        print 'GetHttpData Error: %s' % url
        return ''
    match = re.compile('<meta http-equiv=["]?[Cc]ontent-[Tt]ype["]? content="text/html;[\s]?charset=(.+?)"').findall(httpdata)
    if len(match)>0:
        charset = match[0]
    if charset:
        charset = charset.lower()
        if (charset != 'utf-8') and (charset != 'utf8'):
            httpdata = httpdata.decode(charset, 'ignore').encode('utf8', 'ignore')
    return httpdata



def rootList(page=None):
	if page:
		currpage = int(page)
	else :
		currpage = 1
	url = "http://www.moko.cc/moko/post/%d.html" %currpage

	link = GetHttpData(url)
	match0 = re.compile('<div class="w970">(.+?)<!-- 展示模块 end -->', re.DOTALL).search(link)
	match_url = re.compile('<a href="(/post/\d*\.html)"').findall(match0.group(1))
	match_name = re.compile('class="nickname" >(.+?)</a>').findall(match0.group(1))
	match_img = re.compile('<img src2="(http://.*\.jpg)" />').findall(match0.group(1))
	totalItems = len(match_url)

	if currpage > 1:
		u = sys.argv[0]+"?page=%d" %(currpage-1)
		li = xbmcgui.ListItem("上一页..")
		xbmcplugin.addDirectoryItem(int(sys.argv[1]),u,li,True)

	for i in range(totalItems):
		url = match_url[i]
		name = match_name[i]

		u = sys.argv[0]+"?mode=1&name="+urllib.quote_plus(name)+"&url="+urllib.quote_plus(url)
		li = xbmcgui.ListItem(name, iconImage=match_img[i])
		xbmcplugin.addDirectoryItem(int(sys.argv[1]),u,li,True,totalItems)

	if currpage < 10:
		u = sys.argv[0]+"?page=%d" %(currpage+1)
		li = xbmcgui.ListItem("下一页..")
		xbmcplugin.addDirectoryItem(int(sys.argv[1]),u,li,True)
	
	xbmcplugin.endOfDirectory(int(sys.argv[1]))


def progList(name,url):
	url = 'http://www.moko.cc' + url
	print url
	link = GetHttpData(url)

	match0 = re.compile('<div class="article" id="postContentDiv">(.+?)<div class="dBd">', re.DOTALL).search(link)
	match = re.compile('<img src2="(http://.*\.jpg)"').findall(match0.group(1))

	j = 1
	for i in match:
		li = xbmcgui.ListItem(str(j), iconImage=i)
		j = j + 1
		xbmcplugin.addDirectoryItem(int(sys.argv[1]),i,li,False)

	xbmcplugin.endOfDirectory(int(sys.argv[1]))


def get_params():
    param = []
    paramstring = sys.argv[2]
    if len(paramstring) >= 2:
        params = sys.argv[2]
        cleanedparams = params.replace('?', '')
        if (params[len(params) - 1] == '/'):
            params = params[0:len(params) - 2]
        pairsofparams = cleanedparams.split('&')
        param = {}
        for i in range(len(pairsofparams)):
            splitparams = {}
            splitparams = pairsofparams[i].split('=')
            if (len(splitparams)) == 2:
                param[splitparams[0]] = splitparams[1]
    return param

params = get_params()
mode = None
name = None
url = None
page = None

try:
    url = urllib.unquote_plus(params["url"])
except:
    pass
try:
    name = urllib.unquote_plus(params["name"])
except:
    pass
try:
    mode = int(params["mode"])
except:
    pass
try:
    page = int(params["page"])
except:
    pass

if mode == None:
	rootList(page)
elif mode == 1:
	progList(name, url)